package com.huazai.controller;

import com.huazai.bean.po.User;
import com.huazai.service.BookService;
import com.huazai.service.BorrowService;
import com.huazai.service.FileService;
import com.huazai.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.huazai.service.impl.UserServiceImpl.*;

@Controller
@Transactional
@RequestMapping("/user")
public class UserController {
    private static final String AUTHORITY_GENERAL = "general";
    private static final String AUTHORITY_ADMIN = "admin";
    private UserService userService;
    private FileService fileService;
    private BorrowService borrowService;

    @Autowired
    @Qualifier("BorrowServiceImpl")
    public void setBorrowService(BorrowService borrowService) {
        this.borrowService = borrowService;
    }

    @Autowired
    @Qualifier("FileServiceImpl")
    public void setFileService(FileService fileService) {
        this.fileService = fileService;
    }

    @Autowired
    @Qualifier("UserServiceImpl")
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping("/toUserPaper")
    public String toUserPaper(Model model) {
        //查出所有用户的所有的数据
        List<User> userList = userService.getUserCustom(null, null);
        model.addAttribute("userList", userList);
        //删除userList里面的超级账户
        userList.removeIf(nextUser -> "2963095996@qq.com".equals(nextUser.getEmail()));

        return "user/allUser";
    }

    @RequestMapping("/queryUser")
    public String queryUserByName(@RequestParam("userName") String userName,
                                  Model model) {
        //注意：此处是根据用户名模糊查询出来的结果。
        List<User> userList = userService.getUserByName(userName);

        if (userList.isEmpty()) {
            model.addAttribute("queryMessage", "未查到指定用户");
        } else {
            model.addAttribute("queryMessage", "已找到指定用户");
        }
        model.addAttribute("userList", userList);

        return "user/allUser";
    }

    @RequestMapping("/toEditUser")
    public String toEditPaper(@RequestParam("email") String email,
                              Model model) {

        User user = userService.getUserCustom(null, email).get(0);
        model.addAttribute("user", user);
        String userProfilePath = user.getProfilePath();
        model.addAttribute("filePath", userProfilePath);

        return "user/editUser";
    }

    @RequestMapping("/editUser")
    public String editUser(@RequestParam(value = "file", required = false) CommonsMultipartFile file,
                           HttpSession session,
                           User user) {
        Boolean result = this.editUserService(file, session, user);
        return "redirect:/user/toUserPaper";
    }

    @RequestMapping("/editMyself")
    public String editMyself(@RequestParam(value = "file", required = false) CommonsMultipartFile file,
                             HttpSession session,
                             User user) {
        Boolean result = this.editUserService(file, session, user);
        return "redirect:/book/query";
    }

    private Boolean editUserService(CommonsMultipartFile file,
                                   HttpSession session,
                                   User user) {
        if (file != null && file.getSize() != 0) {
            ServletContext servletContext = session.getServletContext();
            String uploadPath = servletContext.getRealPath("/upload/user");
            String newName = fileService.uploadFileByPath(file, uploadPath, user.getEmail(), user.getProfilePath());
            user.setProfilePath("/upload/user/" + newName);
        }
        System.out.println("user = " + user);
        userService.updateUserMessage(user);
        return true;
    }

    @RequestMapping("/deleteUser")
    public String deleteUser(@RequestParam("email") String email) {

        Map<String, String> map = new HashMap<>();
        map.put("borrowerEmail", email);

        List<String> userAllBorrowID = borrowService.getUserAllBorrowID(email);

        for (String borrowID : userAllBorrowID) {
            borrowService.restoreBookCount(borrowID);
        }

        borrowService.deleteApplyCustom(map);
        userService.deleteUserByEmail(email);

        return "redirect:/user/toUserPaper";
    }


    @RequestMapping("/active")
    public String activeUser(@RequestParam("code") String code,
                             Model model) {
        if (userService.activateUser(code)) {
            return "user/activeSuccess";
        } else {
            model.addAttribute("result", "激活失败，请稍后重试。");
            return "user/message";
        }
    }

    /**
     * 注册相关的所有代码。
     */
    @RequestMapping("/toSignupPaper")
    public String toSignupPaper() {
        return "user/signup";
    }

    @RequestMapping("/signupGeneral")
    public String signUserGeneral(User user, Model model) {

        user.setAuthority(AUTHORITY_GENERAL);
        return userRegistration(user, model);
    }

    @RequestMapping("/signupAdmin")
    public String signUserAdmin(User user, Model model) {

        user.setAuthority(AUTHORITY_ADMIN);
        return userRegistration(user, model);
    }


    public String userRegistration(User user, Model model) {
        if (user.getEmail() == null
                || user.getUserName() == null
                || user.getPassword() == null) {
            model.addAttribute("result", "用户信息为空，注册失败");
            return "user/message";
        }

        String result = userService.userRegistration(user);
        switch (result) {
            case SIGN_SUCCESS:
                //正常注册后，用户的信息应该存在session里面。
                model.addAttribute("result", "注册成功！已经发送激活邮件到你的QQ邮箱（注意：未激活的用户是不能使用的）");
                return "user/message";

            case USER_HAS_EXIST:
                model.addAttribute("result", USER_HAS_EXIST);
                return "user/message";

            case SIGN_FAILED:
                model.addAttribute("result", SIGN_FAILED);
                return "user/message";
            default:
                return "redirect:/door/toLoginPaper";
        }

    }

    @RequestMapping("/toUserInforPaper")
    public String toUserInforPaper(@RequestParam("email") String email,
                                   Model model) {
        List<User> userCustom = userService.getUserCustom(null, email);
        model.addAttribute("user", userCustom.get(0));
        return "user/userInfor";
    }

    @RequestMapping("/changePassword")
    public String changePassword(@RequestParam("password") String password,
                                 @RequestParam("email") String email,
                                 Model model) {
        User user = new User();
        user.setPassword(password);
        user.setEmail(email);
        Boolean changeResult = userService.updateUserMessage(user);
        if (changeResult) {
            model.addAttribute("result", "修改密码成功！");
        } else {
            model.addAttribute("result", "修改密码失败！");
        }
        return "user/message";
    }
}
